<?php

namespace App\Console\Commands\Lib;


use Carbon\Carbon;

/**
 * 需要一个时间的命令计划使用
 * Trait DataDate
 * @package App\Console\Commands\Lib
 */
trait ByHour
{
    /**
     * 开始时间
     * @var Carbon
     */
    protected $start;

    /**
     * 结束时间
     * @var Carbon
     */
    protected $end;

    /**
     * 当前时间
     * 
     * @var Carbon
     */
    protected $current;

    /**
     * 拉取前一天数据的时间范围，必须H:i:s格式，作为闭区间
     * @var array
     */
    private $rerunTimeRange = ['00:00' => '00:30'];

    /**
     * 获取拉取前一天数据的时间范围
     * @return array
     */
    public function getRerunTimeRange()
    {
        return $this->rerunTimeRange;
    }

    /**
     * 设置拉取前一天数据的时间范围
     * @param array $range
     */
    protected function setRerunTimeRange($range)
    {
        $this->rerunTimeRange = $range;
    }

    /**
     * 初始化拉取时间段，默认是当前时间一小时内
     */
    private function initTime()
    {
        $start = call_user_func([$this, 'argument'], 'start');
        if ($start) {
            $this->current = Carbon::parse(date('Y-m-d H:00:00', $start));
            $this->start = Carbon::parse(date('Y-m-d H:00:00', $start))->subHour()->startOfHour();
        } else {
            $this->current = Carbon::now()->startOfHour();
            $this->start = Carbon::now()->subHour()->startOfHour();
        }

        $end = call_user_func([$this, 'argument'], 'end');
        if ($end) {
            $this->end = Carbon::parse(date('Y-m-d H:59:59', $end))->endOfHour();
        } else {
            $this->end = Carbon::parse($this->start)->endOfHour();
        }
    }

    /**
     * 获取起始时间
     * 
     * @param bool $timestamp
     * @return false|string
     */
    protected function getStart($timestamp = false)
    {
        if (!$this->start) {
            $this->initTime();
        }
        return $timestamp ? $this->start->timestamp : (string)$this->start;
    }

    /**
     * 获取结束时间
     * 
     * @return Carbon
     */
    protected function getEnd($timestamp = false)
    {
        if (!$this->end) {
            $this->initTime();
        }
        return $timestamp ? $this->end->timestamp : (string)$this->end;
    }

    /**
     * 获取时间区间
     * @param bool $timestamp
     * @return mixed
     */
    protected function getPeriod($timestamp = false)
    {
        if (!$this->start) {
            $this->initTime();
        }
        return $timestamp ? [$this->start->timestamp, $this->end->timestamp] : [(string)$this->start, (string)$this->end];
    }

    /**
     * 获取几天前的日期
     * @param $days
     * @param bool $timestamp
     * @return int|string
     */
    protected function getCurrentTime($timestamp = false)
    {
        if (!$this->current) {
            $this->initTime();
        }
        return $timestamp ? $this->current->timestamp : (string)$this->current;
    }


    /**
     * 判断此时是否为重跑
     * @return bool
     */
    protected function isRerun()
    {
        return $this->start->timestamp <= $this->getEnd()->subDay()->timestamp;
    }
}
